package com.heihei.serviceimpl.res;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.heihei.common.response.ResponseVO;
import com.heihei.entity.res.ResResourceTagEntity;
import com.heihei.mapper.res.ResResourceTagMapper;
import com.heihei.service.res.ResResourceTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heihei.vo.res.ResResourceIdAndTagVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 资源和标签的中间表 服务实现类
 * </p>
 *
 * @author duanhengfei
 * @since 2021-11-23
 */
@Service
public class ResResourceTagServiceImpl extends ServiceImpl<ResResourceTagMapper, ResResourceTagEntity> implements ResResourceTagService {

    /**
     * 添加
     *
     * @author duanhf
     * 2021年12月06日 13:33:55
     */
    @Override
    public ResponseVO<String> myAdd(ResResourceTagEntity paramEntity) {
        paramEntity.setId(null);
        if(StringUtils.isEmpty(paramEntity.getResourceId())) {
            return ResponseVO.paramLess("资源ID不能为空");
        }
        if(StringUtils.isEmpty(paramEntity.getTagId())) {
            return ResponseVO.paramLess("标签ID不能为空");
        }
        //校验是否已有该记录
        //如果已有该记录，则返回该记录id
        LambdaQueryWrapper<ResResourceTagEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ResResourceTagEntity::getResourceId, paramEntity.getResourceId())
                .eq(ResResourceTagEntity::getTagId, paramEntity.getTagId());
        List<ResResourceTagEntity> list = this.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list)) {
            return ResponseVO.dealSuccess(list.get(0).getId());
        }
        //正常执行添加逻辑
        boolean flag = this.save(paramEntity);
        if(!flag) {
            return ResponseVO.dealFail("可能未添加成功");
        }
        //返回添加成功消息
        return ResponseVO.dealSuccess(paramEntity.getId());
    }

    /**
     * 根据资源id，删除该资源的所有与标签关联信息
     *
     * @author duanhf
     * 2021年12月07日 15:05:25
     */
    @Override
    public boolean deleteByResourceId(String resourceId) {
        UpdateWrapper<ResResourceTagEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(ResResourceTagEntity::getResourceId, resourceId);
        return this.remove(updateWrapper);
    }

    /**
     * 根据资源idList，查询这些资源各自关联的标签信息
     *
     * @author duanhf
     * 2021年12月09日 10:14:36
     */
    @Override
    public List<ResResourceIdAndTagVO> selectTagWithResIdList(List<String> resIdList, Integer delFlag) {
        List<ResResourceIdAndTagVO> list = this.baseMapper.selectTagWithResIdList(resIdList, delFlag);
        return list;
    }
}
